<template>
  <div class="nature-add-or-edit">
    <el-form ref="natureForm" v-model="form" label-position="left" inline class="demo-table-expand">
      <el-form-item prop="src" label="物品贴图">
        <ossUpload :imageUrl="form.src ? domain + form.src : ''" :imgName="randomName" @upload-img="handlerUpload" />
      </el-form-item>
      <el-form-item prop="name" label="中文名称">
        <el-input v-model="form.name" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="alis" label="英文名称">
        <el-input v-model="form.alis" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="tag" label="标签">
        <el-select v-model="form.tag" multiple placeholder="请选择">
          <el-option v-for="item in options" :key="item._id" :label="item.name" :value="item._id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="createScience" label="可制作科技">
        <CompositionItem :selectedArr.sync="form.createScience" :showNum="false" :module="['materials']"
          :mid="$route.query.mid" />
      </el-form-item>
      <el-form-item prop="origin" label="来源">
        <CompositionItem :selectedArr.sync="form.origin" :showNum="false" :module="['natures', 'anims']"
          :mid="$route.query.mid" />
      </el-form-item>
      <el-form-item prop="damage" label="伤害">
        <el-input v-model="form.damage" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="durable" label="耐久">
        <el-input v-model="form.durable" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="defense" label="防御">
        <el-input v-model="form.defense" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="san" label="影响理智">
        <el-input v-model="form.san" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="dampproof" label="防潮">
        <el-input v-model="form.dampproof" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="thermalInsulation" label="隔热">
        <el-input v-model="form.thermalInsulation" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="keepWarm" label="保暖">
        <el-input v-model="form.keepWarm" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="console" label="生成代码">
        <el-input v-model="form.console" placeholder="请输入内容"></el-input>
      </el-form-item>
      <el-form-item prop="extraLink" label="额外链接">
        <ExtraCompositionItem :selectedArr.sync="form.extraLink" :mid="$route.query.mid" :module="module" />
      </el-form-item>
      <el-form-item prop="extraLink" label="额外属性">
        <ExtraProperty :list.sync="form.extraProperty" />
      </el-form-item>
      <mavon-editor v-model="form.introduce" @imgAdd="imgUpload" class="editor-sty" :boxShadow="false" ref="md">
      </mavon-editor>
    </el-form>
    <el-button type="primary" @click="addItem" style="margin-top: 16px">{{
      $route.query.type === "edit" ? "更新" : "提交"
      }}</el-button>
  </div>
</template>

<script>
  import ossUpload from "@/components/ossUpload.vue";
  import CompositionItem from "@/components/CompositionItem.vue";
  import ExtraCompositionItem from "@/components/ExtraCompositionItem.vue";
  import ExtraProperty from "@/components/ExtraProperty.vue";
  import md5 from "md5-js";
  import OSS from "ali-oss";

  export default {
    name: "natureAddOrEdit",
    data() {
      return {
        options: [], // 标签选择项
        searchData: [],
        module: ["materials", "foods", "anims", "natures", "heros"],
        form: {
          src: "",
          name: "",
          alis: "",
          tag: [],
          damage: "",
          durable: "",
          defense: "",
          san: "",
          dampproof: "",
          thermalInsulation: "",
          keepWarm: "",
          console: "",
          introduce: "",
          createScience: [],
          origin: [],
          extraLink: [],
          extraProperty: []
        },
      };
    },
    components: {
      ossUpload,
      CompositionItem,
      ExtraCompositionItem,
      ExtraProperty
    },
    computed: {
      randomName: {
        get: function () {
          let time = new Date();
          return md5(time);
        },
        cache: false,
      },
    },
    async activated() {
      await this.getTag();
      if (this.$route.query.type === "edit") {
        this.fetchDetail();
      }
    },
    deactivated() {
      this.form = {
        src: "",
        name: "",
        alis: "",
        tag: [],
        damage: "",
        durable: "",
        defense: "",
        san: "",
        dampproof: "",
        thermalInsulation: "",
        keepWarm: "",
        console: "",
        introduce: "",
        createScience: [],
        origin: [],
        extraLink: [],
        extraProperty: []
      };
    },
    methods: {
      /**
       * 获取详情数据
       **/
      async fetchDetail() {
        let res = await this.axios.get("nature/single", {
          params: {
            id: this.$route.query.id,
          },
        });
        let temp = this.showDataTransform(res.data, [
          { needNum: false, key: "createScience" },
          { needNum: false, key: "origin" },
          { hasList: true, key: "extraLink" }
        ]);
        temp.tag = temp.tag.map((val) => {
          return val._id;
        });
        this.form = temp;
      },
      /**
       * @description 获取自然对应的标签
       */
      async getTag() {
        let res = await this.$store.dispatch("getTags", {
          kind: "natures",
          mid: this.$route.query.mid,
        });
        this.options = res;
      },
      /**
       * @description 自然新增或修改
       */
      async addItem() {
        let requestUrl =
          this.$route.query.type === "edit" ? "/nature/update" : "/nature/add";
        let [_createScience, _origin] = this.transformSumbitData([
          {
            list: this.form.createScience,
            needNum: false,
          },
          {
            list: this.form.origin,
            needNum: false,
          },
        ]);
        let _extraLink = this.transformSumbitDataList(this.form.extraLink)
        let res = await this.axios.post(requestUrl, {
          version: this.$store.state.version,
          ...this.form,
          createScience: _createScience,
          origin: _origin,
          extraLink: _extraLink
        });
        if (!res.data.code) {
          this.$message.success("添加成功");
          this.$router.go(-1);
        }
      },
      handlerUpload(src) {
        this.form.src = src;
      },
      /**
       * 图片上传
       */
      imgUpload(filename, $file) {
        // oss配置
        const client = new OSS({
          endpoint: "oss-cn-beijing.aliyuncs.com",
          accessKeyId: "LTAI4FgrsFXo8ij335BxeRbp",
          accessKeySecret: "oG0PWkV0qOeDoJQfwEHOqIvTp16S0x",
          bucket: "stavebox",
        });
        // 图片路径拼接，dirName其实就是定义存在oss的哪个虚拟文件夹下的
        let time = new Date();
        let hash = md5(time);
        let imgType = $file.type.split("/")[1];
        let hashName = "Article/" + hash + "." + imgType;
        // 将文件流上传至oss
        client
          .put(hashName, $file)
          .then((res) => {
            let imgUrl = this.domain + res.name;
            this.$refs.md.$img2Url(filename, imgUrl);
          })
          .catch((err) => {
            console.log(err);
          });
      },
    },
  };
</script>

<style lang="scss">
  .nature-add-or-edit {
    .demo-table-expand {
      font-size: 0;
    }

    .demo-table-expand label {
      width: 120px;
      color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
      margin-right: 0;
      margin-bottom: 16px;
      width: 50%;
    }
  }
</style>
<style lang="scss" scoped>
  .nature-add-or-edit {
    padding: 16px;

    .delete-button,
    .add-button {
      display: inline-block;
      width: 60px;
      flex-shrink: 0;
    }

    .material {
      margin-bottom: 10px;
    }

    .attr-container {
      display: flex;
      height: 50px;
    }
  }
</style>